package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"gopkg.in/gomail.v2"
	"math/rand"
	"net/http"
	"strconv"
	"testGin/entity"
	"testGin/tool"
)

func Register(c *gin.Context) {
	user := entity.GetUser(c)

	// 查询
	//row, _ := Db.Query("select `id` from qiniu.user where , user.Username, user.Email)
	result := GetDB().Where("username = ? or email = ?", user.Username, user.Email).First(&user)
	if result.RowsAffected == 1 {
		// 用户名或者邮箱已存在，有重复
		c.JSON(http.StatusOK, tool.R{
			0, "用户名或者邮箱已存在", nil,
		})
	} else {
		GetDB().Select("username", "password", "email").Create(&user)
		c.JSON(http.StatusOK, tool.R{
			200, "注册成功", nil,
		})
		// 然后跳转到登录界面
	}
}

func SendVerifyEmail(c *gin.Context) {
	user := entity.GetUser(c)
	// 生成6位随机验证码
	code := ""
	for i := 0; i < 6; i++ {
		code = code + strconv.Itoa(rand.Intn(9))
	}
	// 验证码存入redis
	GetRedisConn().Do("set", user.Username, code)
	GetRedisConn().Do("expire", user.Username, 60*5)

	// 发送验证码
	SendMail(user.Email, code)
	c.JSON(http.StatusOK, tool.R{
		200, "发送成功", nil,
	})
}

// 使用第三方库gomail实现邮件的发送
func SendMail(ToEmail string, code string) {
	m := gomail.NewMessage()
	m.SetAddressHeader("From", "2774668116@qq.com", "七小音")
	m.SetHeader("To", ToEmail)
	m.SetHeader("Subject", "牛小音绑定邮箱验证！！！!")
	m.SetBody("text/html", "	您正在牛小音进行邮箱绑定的操作，本次请求的邮件验证码是："+code+"(为了保证您账号的安全性，请您在5分钟内完成验证).\n本验证码5分钟内有效，请及时输入!")
	d := gomail.NewDialer("smtp.qq.com", 465, "2774668116@qq.com", "hnoxipochipadhec")
	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
}

// 验证邮箱验证码
func VerifyEmail(c *gin.Context) {
	data, _ := c.GetRawData()
	var verify entity.VerifyEmail
	_ = json.Unmarshal(data, &verify)

	ser_Code, _ := redis.String(GetRedisConn().Do("get", verify.UserName))
	cli_Code := verify.Code
	if ser_Code == cli_Code {
		c.JSON(http.StatusOK, tool.R{
			200, "验证通过", nil,
		})
	} else {
		c.JSON(http.StatusOK, tool.R{
			0, "验证未通过", nil,
		})
	}
}
